# -*- coding: utf-8 -*-
"""
Created on Wed Apr 24 14:05:18 2024

@author: 1
"""
import numpy as np  
  
# 分段阶跃信号函数
# 单位阶跃函数，t1代表阶跃位置
def u(t, t1):  
    return (t > t1).astype(int)  
# 充气速率信号函数Fi(t) 
def Fi(x, n, t1, tp, mc):  
    y_sum = 0  # 初始化y的和为0  
    for i in range(n):  
        # 计算当前迭代中的y_i  
        y_i = mc*(u(x, i * tp) - u(x, i * tp + t1) )
        # 累加到y_sum中  
        y_sum += y_i  
    return y_sum
# 放气速率信号函数Fe(t) 
def Fe(x, n, t2, t3, tp, md):  
    y_sum = 0  # 初始化y的和为0  
    for i in range(n):  
        # 计算当前迭代中的y_i  
        y_i = md*(u(x, i * tp + t3) - u(x, i * tp + t2) )
        # 累加到y_sum中  
        y_sum += y_i  
    return y_sum

# 线型生成器
def linesstyle_generator():
    linestyle = ['-', '--', '-.',':']
    lineID = 0
    while True:
        yield linestyle[lineID]
        lineID = (lineID + 1) % linestyle

# 完善绘图函数
def plot_set(fig_ax, *args):
    fig_ax.set_xlabel(args[0]) # 参数1设置x轴标签
    fig_ax.set_ylabel(args[1]) # 参数2设置y轴标签
    fig_ax.grid(ls=':')
    if len(args)==3:
        fig_ax.legend(loc=args[2]) # 参数3设置图例位置

# 伯德图
def bodeplot_set(fig_ax, *args):
    # 设置幅频图的网格和y轴的标签
    fig_ax[0].grid(which="both", ls=':')
    fig_ax[0].set_ylabel('Gain [dB]') # 图y轴表示幅值[dB]
    # 设置相频图的网格和x轴、y轴的标签
    fig_ax[1].grid(which="both", ls=':') 
    fig_ax[1].set_xlabel('$\omega$ [rad/s]') # 图x轴表示频率
    fig_ax[1].set_ylabel('Phase [deg]') # 图y轴表示相位[deg]
    # 显示图例
    if len(args) > 0:
        fig_ax[1].legend(loc=args[0]) # 参数大于等于1，显示幅频图
    if len(args) > 1:
        fig_ax[0].legend(loc=args[1]) # 参数大于等于2，同时显示相频图


# 参数设置  
t1 = 8
t2 = 12
t3 = 16 
tp = 24  
n = 5  # 示例中n设置为3，您可以根据需要更改这个值  
CD = t1 / (t3 - t2)
mc = 1
md = CD

# 生成输入数组x  
x = np.linspace(0, n * tp, 200)  
  
# 计算y  
yc = Fi(x, n, t1, tp, mc)  
yd = Fe(x, n, t2, t3, tp, md)
y = yc + yd  
# 打印结果或进行其他操作  
print(y)

# Plotting the signal
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.xlabel('Time')
plt.ylabel('Signal')
plt.title('Periodic Step Signal')
plt.grid(True)
plt.show()